﻿using System;
using System.ComponentModel.Composition;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Web.Helpers.UrlShortener.Core;

namespace Microsoft.Web.Helpers.UrlShortener.Bitly
{
    [Export(UrlShortenerStrings.PROVIDER_NAME_Bitly, typeof(IUrlShortener))]
    [PartCreationPolicy(CreationPolicy.NonShared)] 
    public class Shorten : IUrlShortener
    {
        //V3 Url
        public const string bitlyUrlRequest = "http://api.bit.ly/v3/shorten?login={0}&apiKey={1}&longUrl={2}&format=xml";

        public string Shortern(string uriToShrink, dynamic settings )
        {
            ValidateSettings(settings);

            string apiKey = settings.ApiKey;
            string userName = settings.UserName;
            
            string requestFormat = bitlyUrlRequest;
            if (null != settings.RequestFormat)
                requestFormat = settings.RequestFormat;

            string requstString = this.formatRequest(uriToShrink, requestFormat, userName, apiKey);
            var bitlyResult = this.callBitly(requstString);

            return bitlyResult;
        }

        private string formatRequest(string uriToShrink, string requestFormat, string userName, string apiKey)
        {
            string requestUrl =
                string.Format(
                    requestFormat,
                    userName,
                    apiKey,
                    uriToShrink );

            return requestUrl;
        }

        private string callBitly(string requestUrl)
        {
            XDocument doc = XDocument.Load(requestUrl);
            XName xName = "url";

            return doc.Descendants(xName).First().Value;
        }

        public void ValidateSettings( dynamic settings )
        {
            string userName = settings.UserName as string;
            string apiKey = settings.ApiKey as string;

            if (String.IsNullOrEmpty( userName ) || string.IsNullOrEmpty( apiKey ))
                throw new ConfigurationException("UrlHelper was expecting Settings.ApiKey and Settings.UserName Populated.  One or both of them are not");
        }
    }
}
